<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Area;
use App\Http\Requests\AreaRequest;
use Cache;
use App\Models\PriDeviceInfo;
use App\Models\Phpwarn;
use App\Models\SyUser;

class NewAreaController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = Area::get()->toTree()->toArray();
        
        $this->formatChildren($data);

        return [ 'data' => $data ];
    }

    //格式化子数据
    protected function formatChildren(&$data)
    {
        foreach ($data as &$v) {
            if (!empty($v['children'])) {
                $this->formatChildren($v['children']);
            } else {
                unset($v['children']);
            }
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(AreaRequest $request)
    {
		$data = $request->input();
        $parentId=array_get($data, 'Fid', 0);
		
		$parent = Area::find($parentId);
        $area = Area::create($data, $parent);
		
        if(!$area){
            return $this->error('添加失败');
        }
        $this->setDefaultArea($request, $area);
        $this->addAction(['sy_area']);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(AreaRequest $request, $id)
    {
		$data = $request->input();
		
        $area = Area::findOrFail($id);
		$area->fill($data);

        if(!$area->save($data)){
            return $this->error('保存失败');
        }
        $this->setDefaultArea($request, $area);

        $this->addAction(['sy_area']);
    }
	
	//设置默认区域
	protected function setDefaultArea($request, $data) {
		$isDefault = $request->is_default;
		$cid = data_get($data, 'Co_ID');
        $cacheKey="company:area:".$cid;

        if(!$isDefault) {
            Cache::forget($cacheKey);
        }else{
            $data = $data->toArray();
            Cache::forever($cacheKey, $data);
        }

	}

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //whereDescendantOrSelf
        $area = Area::findOrFail($id);
        $areaIds = $area->descendants->pluck('AreaId')->toArray();
        $areaIds[] = $id;

        if(!$area->delete()){
            return $this->error('删除失败');
        }
        $cid = $area->Co_ID;
        //删除区域设备
        PriDeviceInfo::searchCompany($cid)->whereIn('AreaId', $areaIds)->delete();
        //删除实时告警
        Phpwarn::company($cid)->whereIn('pdi_areaid', $areaIds)->delete();

        //删除缓存
        $cacheKey="company:area:".$cid;
        Cache::forget($cacheKey); 

        //清除用户站点
        SyUser::whereIn('scope', $areaIds)->update(['scope'=>null]);

        $this->addAction(['t_prideviceinfo', 'sy_area', 't_phpwarn']);
    }

    /**
     * 获取区域设备
     */
    public function device($areaid)
    {
        $info = Area::findOrFail($areaid);

        $device = PriDeviceInfo::site($areaid)
            ->select(['AreaId', 'pdi_index', 'dpt_id', 'pdi_name', 'DragX', 'DragY', 'ts_Icon'])
            ->leftJoin('t_Subdevicetype', function($join) {
                $join->on('t_Subdevicetype.ts_Maintypeid', '=', 't_prideviceinfo.dpt_id')->on('t_Subdevicetype.ts_typeid', '=', 't_prideviceinfo.SubType');
            })
            ->with(['types' => function($query){
                $query->select(['dt_typeid', 'dt_icon']);
            }])
            ->withCount('realWarn')
            ->get();

        $areaImg = $info->area_img;

        return [ 'data' => $device, 'areaImg' => $areaImg ];
    }
}
